package com.ruoyi.web.controller.qiyefuwu;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.system.projectfiles.domain.TFileUpload;
import com.ruoyi.system.projectfiles.service.ITFileUploadService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;

import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文档管理Controller
 *
 * @author ruoyi
 * @date 2024-05-15
 */
@RestController
@RequestMapping("/system/upload")
public class TFileUploadController extends BaseController {
    @Autowired
    private ITFileUploadService tFileUploadService;

    @Autowired
    ServerConfig serverConfig;

    /**
     * 查询文档管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:upload:list')")
    @GetMapping("/list")
    public TableDataInfo list(TFileUpload tFileUpload) {
        startPage();
        List<TFileUpload> list = tFileUploadService.selectTFileUploadList(tFileUpload);
        return getDataTable(list);
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    public AjaxResult uploadFiles(List<MultipartFile> files) throws Exception {
        try {
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                newFileNames.add(FileUtils.getName(fileName));
                originalFilenames.add(file.getOriginalFilename());
            }
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, File.separator));
            ajax.put("fileNames", StringUtils.join(fileNames, File.separator));
            ajax.put("newFileNames", StringUtils.join(newFileNames, File.separator));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, File.separator));
            return ajax;
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }


    /**
     * 导出文档管理列表
     */
    @PreAuthorize("@ss.hasPermi('system:upload:export')")
    @Log(title = "文档管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TFileUpload tFileUpload) {
        List<TFileUpload> list = tFileUploadService.selectTFileUploadList(tFileUpload);
        ExcelUtil<TFileUpload> util = new ExcelUtil<TFileUpload>(TFileUpload.class);
        util.exportExcel(response, list, "文档管理数据");
    }

    /**
     * 获取文档管理详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:upload:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(tFileUploadService.selectTFileUploadById(id));
    }

    /**
     * 新增文档管理
     */
    @PreAuthorize("@ss.hasPermi('system:upload:add')")
    @Log(title = "文档管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TFileUpload tFileUpload) {
        return toAjax(tFileUploadService.insertTFileUpload(tFileUpload));
    }

    /**
     * 修改文档管理
     */
    @PreAuthorize("@ss.hasPermi('system:upload:edit')")
    @Log(title = "文档管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TFileUpload tFileUpload) {
        return toAjax(tFileUploadService.updateTFileUpload(tFileUpload));
    }

    /**
     * 删除文档管理
     */
    @PreAuthorize("@ss.hasPermi('system:upload:remove')")
    @Log(title = "文档管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(tFileUploadService.deleteTFileUploadByIds(ids));
    }
}
